package cn.edu.zafu.bigdata.lwg;

import java.io.*;
import java.net.*;

public class TCPServer {
    public static void main(String[] args) {
        try {
            // 创建服务器端的Socket，监听端口号1234
            ServerSocket serverSocket = new ServerSocket(8888);
            System.out.println("服务器启动，等待客户端连接...");

            // 服务器无限循环，等待客户端连接
            while (true) {
                // 等待客户端连接
                Socket socket = serverSocket.accept();
                System.out.println("客户端已连接");

                // 获取输入流，用于接收客户端发送的消息
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                // 获取输出流，用于给客户端发送消息
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

                // 循环接收客户端消息，并回复
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    System.out.println("客户端说：" + inputLine);
                    String response = "服务器回复：" + inputLine;
                    out.println(response);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class TCPClient {
    public static void main(String[] args) {
        try {
            // 创建客户端的Socket，连接服务器的IP地址和端口号
            Socket socket = new Socket("192.168.16.73", 8888);
            System.out.println("已连接到服务器");

            // 获取输出流，用于给服务器发送消息
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            // 获取输入流，用于接收服务器的回复
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            // 获取系统输入流，用于输入消息
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
            String userInput;

            // 循环发送消息给服务器，并接收回复
            while ((userInput = stdIn.readLine()) != null) {
                out.println(userInput);
                System.out.println("服务器回复：" + in.readLine());
            }
        } catch (UnknownHostException e) {
            System.out.println("服务器地址错误");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("无法连接到服务器");
            e.printStackTrace();
        }
    }
}
